<template>
  <el-button type="primary" v-if="route.query.categoryLevel>1" @click="backfun" :icon="ArrowLeftBold" circle />分类管理
  <!-- {{ multipleSelection }} -->
  <!-- <h1> 商品编号 11000-12999</h1> -->
  <el-button type="success" @click="addBtnFun">
    <el-icon>
      <Plus />
    </el-icon>
    添加</el-button>
  <el-button @click="bigdel" type="danger">
    <el-icon><Delete /></el-icon>
    批量删除</el-button>
  <el-table ref="multipleTableRef" :data="listone" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column label="分类名称" width="120">
      <template #default="scope">{{ scope.row.categoryName }}</template>
    </el-table-column>
    <el-table-column property="categoryRank" label="排序值" />
    <el-table-column property="createTime" label="添加时间" />

    <el-table-column label="操作">
      <template #default="scope">
        <!-- {{ scope.row.redirectUrl }} -->
        <el-button size="small" type="primary" @click="handlePut(scope.$index, scope.row)">
          修改
        </el-button>
        <el-button size="small" type="primary" @click="handlenext(scope.$index, scope.row)">
          下级分类
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>






  <!-- 弹框 -->
  <el-dialog v-model="dialogFormVisible" :title=title width="500" @closed="closed">
    <!-- 文件 -->
    <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" label-width="auto">



      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="ruleForm.categoryName" />
      </el-form-item>

      <el-form-item label="排序值" prop="categoryRank">
        <el-input v-model="ruleForm.categoryRank" />
      </el-form-item>




      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
        <el-button @click="dialogFormVisible = false;">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>



  <!-- 分页 -->

  <el-pagination background @current-change="currentChange" layout="prev, pager, next" :total="total" />

</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
import { ElTable } from 'element-plus'
import axios from '../../ajax';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'
let route = useRoute()
let router = useRouter()
let dialogFormVisible = ref(false)
let title = ref('添加')
let carouselId = "";//id
import { ArrowLeftBold,Plus, Delete } from '@element-plus/icons-vue'

const multipleTableRef = ref()

const multipleSelection = ref([])
// const toggleSelection = (rows) => {
//   if (rows) {
//     rows.forEach((row) => {
//       // TODO: improvement typing when refactor table
//       // eslint-disable-next-line @typescript-eslint/ban-ts-comment
//       // @ts-expect-error
//       multipleTableRef.value.toggleRowSelection(row, undefined)
//     })
//   } else {
//     multipleTableRef.value.clearSelection()
//   }
// }
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
//拿数据
onMounted(() => {// 刚进页面显示一级分类
  let { categoryLevel, parentId } = route.query
  getdata(categoryLevel, parentId, 1);
})
let listone = ref([])
let total = ref(0)

let getdata = async (categoryLevel, parentId, pageNumber) => { //表单数据 封装
  let { list, totalCount } = await axios.get('/categories', {
    params: {
      pageNumber,
      pageSize: 10,
      categoryLevel,
      parentId
    }
  })
  console.log(list);
  listone.value = list
  total.value = totalCount
  console.log(total.value);
}

//下级分类
let handlenext = (index, row) => {
  let categoryLevel = row.categoryLevel + 1
  let categoryId = row.categoryId
  router.push({
    path: "/index/classify",
    query: {
      categoryLevel: categoryLevel,
      parentId: categoryId
    }
  })
}
onBeforeRouteUpdate((to, from) => {// 路由更新
  let { categoryLevel, parentId } = to.query
  getdata(categoryLevel, parentId, 1);

})

let backfun = () => {
  router.go(-1)
}


//删除
let handleDelete = (i, row) => {
  console.log(row);
  listone.value.splice(i, 1)
  getid([row.categoryId])
}
let getid = async (ids) => {//拿到id
  let res = await axios.delete('/categories/delete', {
    data: {
      ids
    }

  })
}
//批量删除

let bigdel = () => {//删除

if (multipleSelection.value.length == 0) {
  // alert("未选择")
  ElMessage.error('未选择!')
}

let arry = []
multipleSelection.value.map(item => arry.push(item.carouselId))

multipleSelection.value.map(item => {
  listone.value.map((items, index) => {
    if (item.carouselId == items.carouselId) {
      console.log(index);
      listone.value.splice(index, 1)
    }
  })
})


getid(arry)
}



let addBtnFun = () => {//添加
  title.value = "添加"
  dialogFormVisible.value = true
  carouselId = '';
  ruleForm.categoryName = ""
  ruleForm.categoryRank = ''


};
const ruleFormRef = ref()
const ruleForm = reactive({
  categoryName: "",
  categoryRank: '',
  // configType: 3,
})
const rules = reactive({  // 表单验证
  categoryName: [
    { required: true, message: '分类名称', trigger: 'blur' },
  ],
  categoryRank: [
    { required: true, message: '排序', trigger: 'blur' },
  ],

})


//确定
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {//验证通过----ajax
      console.log('submit!')
      if (title.value == '添加') {
        submitfun()
      } else {
        submitfunput()
      }


    } else { // 验证失败
      console.log('error submit!', fields)
    }
  })
}

let submitfun = async () => {//添加
  let res = await axios.post('/categories', {
    categoryName: ruleForm.categoryName,
    categoryRank: ruleForm.categoryRank,
    categoryLevel: route.query.categoryLevel,
 
    parentId: route.query.parentId==1?0:route.query.parentId,

  })
  dialogFormVisible.value = false
  let { categoryLevel, parentId } = route.query
  getdata(categoryLevel, parentId, 1);
}
let submitfunput = async () => {//修改*********************************************
  let res = await axios.put('/categories', {
    categoryName: ruleForm.categoryName,
    categoryRank: ruleForm.categoryRank,
    categoryId: carouselId,//存id
    categoryLevel: route.query.categoryLevel,
 
    parentId: route.query.parentId==1?0:route.query.parentId,

  })
  dialogFormVisible.value = false
  let { categoryLevel, parentId } = route.query
  getdata(categoryLevel, parentId, 1);
}
//修改
let handlePut = (index, row) => {
  title.value = '修改'
  console.log(row);
  dialogFormVisible.value = true
  carouselId = row.categoryId,
    ruleForm.categoryName = row.categoryName,
    ruleForm.categoryRank = row.categoryRank

}
//分页
let currentChange = (page) => {
  console.log(page);
  // getdata(page)
  let { categoryLevel, parentId } = route.query
  getdata(categoryLevel, parentId, page);
}
let closed = () => {

}

</script>

<style lang="scss" scoped>
.el-pagination {
  justify-content: center;
}
</style>